﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

namespace ServerUtils
{
    public static class ExtensionMethodsObject
    {
        public static string Serialize(this object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }

            try
            {
                var type = obj.GetType();
                var serializer = new DataContractSerializer(type);
                var sw = new StringWriter();
                
                using (var xmlw = new XmlTextWriter(sw) { Formatting = Formatting.Indented })
                {
                    serializer.WriteObject(xmlw, obj);
                    return sw.GetStringBuilder().ToString();
                }
            }
            catch (Exception ex)
            {
                return string.Format("Unable to serialize object: Error: {0}", ex.ToString());
            }
        }
    }
}
